<script setup>
import { ref, onMounted } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { userGetUserService, userUpdateAvatarService } from '@/api/user.js'
import { useUserStore } from '@/stores/modules/user.js'
const userStore = useUserStore()
const imageUrl = ref('')
onMounted(() => {
  const userPic = userStore.userInfo.userPic
  if (userPic) {
    imageUrl.value = userPic
  }
})
const handleAvatarChange = (file) => {
  if (file.raw.type !== 'image/png') {
    ElMessage.error('Avatar picture must be PNG format!')
    return
  }
  if (file.raw.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return
  }
  const fileReader = new FileReader()
  fileReader.readAsDataURL(file.raw)
  fileReader.onload = (e) => {
    imageUrl.value = e.target.result
  }
}
const onSubmit = async () => {
  await userUpdateAvatarService(imageUrl.value)
  ElMessage.success('修改成功')
  let res = await userGetUserService()
  userStore.setUserInfo(res.data)
}
</script>

<template>
  <el-card style="max-width: 100%; min-height: 90%; margin: 20px" shadow="hover">
    <template #header>
      <div class="card-header">
        <strong>头像设置</strong>
      </div>
    </template>
    <el-upload
      class="avatar-uploader"
      :show-file-list="false"
      :auto-upload="false"
      :on-change="handleAvatarChange"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar" />
      <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
    </el-upload>
    <template #footer>
      <el-button type="primary" @click="onSubmit">保存</el-button>
    </template>
  </el-card>
</template>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
